package org.eden.rpc.core.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import org.eden.rpc.common.exception.ConnectException;
import org.eden.rpc.core.codec.DefaultDecoder;
import org.eden.rpc.core.codec.DefaultEncoder;
import org.eden.rpc.core.codec.KryoSerializer;
import org.eden.rpc.common.entity.RpcRequest;
import org.eden.rpc.common.entity.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.LockSupport;


public class NettyClient implements RpcClient {

    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);

    public static final AttributeKey<RpcResponse> RESPONSE_ATTRIBUTE_KEY = AttributeKey.valueOf("rpcResponse");

    private final Bootstrap bootstrap;

    private Channel channel;
    private NettyClientHandler handler;

    public NettyClient(String host, int port) {
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(host, port)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new DefaultEncoder<>(new KryoSerializer(), RpcRequest.class));
                        pipeline.addLast(new DefaultDecoder());
                        pipeline.addLast(new NettyClientHandler());
                    }
                });
    }

    public NettyClient(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    @Override
    public Object sendRequest(RpcRequest request) {
        if (isValid()) {
            channel.writeAndFlush(request).addListener(future1 -> {
                if (future1.isSuccess()) {
                    logger.info("发送请求: " + request);
                } else {
                    logger.error("发送请求失败: " + future1.cause());
                }
            });

            // 等待接收结果
            handler.setMasterThread(Thread.currentThread());
            LockSupport.park();
            RpcResponse response = channel.attr(RESPONSE_ATTRIBUTE_KEY).get();
            // TODO 返回状态判断
            return response.getData();
        }
        return null;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public void setHandler(NettyClientHandler handler) {
        this.handler = handler;
    }


    @Override
    public void close() {
        channel.disconnect();
    }

    @Override
    public boolean isValid() {
        return channel.isActive();
    }

    @Override
    public void connect() throws ConnectException{
        try {
            ChannelFuture future = bootstrap.connect().sync();
            channel = future.channel();
            if (channel == null || !channel.isActive()) {
                throw new ConnectException();
            }
            this.handler = channel.pipeline().get(NettyClientHandler.class);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
    }
}
